<?php
require_once 'application/models/Exercice.php';
require_once 'application/models/Batterie.php';

class CsvUtil {
	
	/**
	 * FORMAT :
	 * description;reponse_complete;question 
	 */ 
	
	private static $_instance = null;
	private static $validators = null;
	private static $fields = null;
	
	private $exercices;

	function __construct(){
		$this->exercices = array();
	}
	
	public static function getInstance() {
		if (self::$_instance == null) {
			self::$validators = array(
				TypeChecker::$_TEXT_TYPE, // description
				TypeChecker::$_TEXT_TYPE, // reponse_complete
				TypeChecker::$_TEXT_TYPE // question
			);
			
			self::$fields = array(
				'description',
				'reponse_complete',
				'question'
			);
			
			self::$_instance = new CsvUtil();
		}
		return self::$_instance;
	}
	
	public function check($file) {
		return $this->isCsv($file) && $this->isWellFormed($file);
	}
	
	private function isCsv($file) {
		return !($file["error"] > 0);
	}
	
	private function isWellFormed($file) {
		$this->exercices = array();
		$tmpFileName = $file['tmp_name'];
		$hasError = false;
		$error = "no error";
		$row = 1;
		if (($handle = fopen($tmpFileName, "r")) !== FALSE) {
			while ((($data = fgetcsv($handle, 0, ";")) !== FALSE) && (!$hasError)) {
				$exercice = array();
				$num = count($data);
				if ($num != count(self::$validators)) {
					$hasError = true;
					$error = "nombre d'éléments incorrect à la ligne ".$row;
				} else {
			        for ($c=0; $c < $num; $c++) {
						$isValid = TypeChecker::validate(array(
							array('data' => $data[$c], 'type' => self::$validators[$c], 'name' => self::$fields[$c]),
						));
						if ($isValid !== true) {
							$hasError = true;
							$error = "l'élément ".$c." de la ligne ".$row." est mal formé";
						}
			        	$exercice[self::$fields[$c]] = $data[$c];
			        }
				}
				$this->exercices[] = $exercice;
				$row++;
		    }
		    fclose($handle);
		}
		return !$hasError;
	}
	
	public function save($batterie) {
		$hasError = false;
		$maxQuestion = $batterie['question_per_page'];
		$maxPage = $batterie['page_per_serie'];
		$lastRecord;
		$metaData;
		
		// type id = 2 (always, for now)
		$autoData = array(
		    'batterie_id' => $batterie['id'],
		    'type_id' => 2,
		);
		
		$tableE = new Exercice();
		$tableB = new Batterie();
		
		//TODO: check injection SQL !!
		//TODO: rollback
	    
	    // insert the new exercices
		for($i=0;$i<count($this->exercices) && !$hasError;$i++) {
			$exercice = $this->exercices[$i];
			
			try {
				$data = array_merge($autoData, $exercice);
				
				$lastInsertId = $tableE->insert($data);	    
			}catch(Exception $exception) {
				$hasError = true;
			}
		}
		
		return !$hasError;
	}
		
}